package com.ld.task;

public class TestSemaPhore implements Runnable {

    private UseSemaphore useSemaphore;

    public TestSemaPhore(UseSemaphore useSemaphore){
        this.useSemaphore = useSemaphore;
    }

    @Override
    public void run() {
        try {
            System.out.println("线程"+Thread.currentThread().getName()+"开始获取数据库链接");
            long start = System.currentTimeMillis();
            SimulateCollection simulateCollection = useSemaphore.getCollection();
            long end = System.currentTimeMillis();
            System.out.println("线程"+Thread.currentThread().getName()+"数据库链接获取成功,耗时"+(end-start)+"ms");
            System.out.println("线程"+Thread.currentThread().getName()+"开始工作。。。");
            Thread.sleep(500);
            System.out.println("线程"+Thread.currentThread().getName()+"工作完成释放链接");
            useSemaphore.releaseCollection(simulateCollection);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TestSemaPhore testSemaPhore = new TestSemaPhore(new UseSemaphore(2));
            for (int i=0;i<6;i++){
            new Thread(testSemaPhore).start();
        }
    }
}
